//
//  HomePageUserItemViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/29.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageUserDynamicListViewController.h"
#import "HomePageUserInfoViewController.h"
#import "HomePageDetailViewController.h"

#import "HomeUserInfoDynamicContentViewController.h"
#import "HomeUserInfoDynamicImageViewController.h"
#import "HomePageUserDataController.h"
#import "HomePageNavModel.h"
#import "HomePageItemModel.h"
@interface HomePageUserDynamicListViewController ()<IGListAdapterDataSource,IGListAdapterDelegate,UIScrollViewDelegate>
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,strong)IGListAdapter *adapter;
@property (nonatomic,strong)IGListCollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)HomePageItemModel *lastModel;


@property (nonatomic,assign)BOOL isLastPage;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic,assign)CGFloat lastcontentOffset;

@property (nonatomic,assign)BOOL isTop;

@property (nonatomic,assign)BOOL isBeginScroll;

@property (nonatomic,assign)NSInteger currentIndex;

@property (nonatomic,strong)UIView *dataView;
@property (nonatomic,strong)UILabel *dataLb;

@property (nonatomic,assign)NSInteger lastIndex;

@property (nonatomic,strong)UIView *dataLine;

@property (nonatomic,assign)BOOL isLoadingData;

@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDateLb;


@end

@implementation HomePageUserDynamicListViewController



- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (IGListCollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[IGListCollectionView alloc]initWithFrame:self.view.frame];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (IGListAdapter *)adapter {
    if (!_adapter) {
        _adapter = [[IGListAdapter alloc] initWithUpdater:[[IGListAdapterUpdater alloc] init] viewController:self];
    }
    return _adapter;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.dataArray.count != 0) {
        [self resetConfigure];
        [self updateListStatusSource];
    }
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.collectionView.frame = self.view.bounds;
}


- (void)updateListStatusSource{
    
    self.isBeginScroll = NO;
    self.isLoadingData = NO;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = self.userId;
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(self.page * 10);
    param[@"type"] = @"1";
    param[@"checked"] = @(1);
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPostList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPostList) parames:param success:^(id responseObj) {
        self.isLoadingData = YES;
        if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
            NSArray *resultArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            [resultArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull newObject, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull oldObject, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([newObject.postId isEqualToNumber:oldObject.postId]) {
                        oldObject.isDisplay = newObject.isDisplay;
                        oldObject.likeNum = newObject.likeNum;
                        oldObject.commentNum = newObject.commentNum;
                        oldObject.shareNum = newObject.shareNum;
                        oldObject.followType = newObject.followType;
                        oldObject.unlikeNum = newObject.unlikeNum;
                        oldObject.isUnLike = newObject.isUnLike;
                        oldObject.isLike = newObject.isLike;
                    }
                }];
            }];
            [self.adapter reloadDataWithCompletion:^(BOOL finished) {
                if (finished) {
                    CGFloat bottom = self.collectionView.mj_insetB;
                    self.isLastPage = ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]);
                    if (self.isLastPage) {
                        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                        if (self.collectionView.mj_footer.cl_height == 44.0f) {
                            self.collectionView.mj_footer.cl_height = 138.0f;
                            if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                                 self.collectionView.mj_insetB = 138.0f;
                             }
                        }
                    }else{
                        [self.collectionView.mj_footer resetNoMoreData];
                        if (self.collectionView.mj_footer.cl_height == 138.0f) {
                            self.collectionView.mj_footer.cl_height = 44.0f;
                            if (bottom == 138.0f) {
                                self.collectionView.mj_insetB = 44.0f;
                            }
                        }
                    }
                    if (self.updateItemCount) {
                        self.updateItemCount([responseObj[RESPONSE][TOTAL] intValue]);
                    }
                }
                self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
            }];
        }
    } failure:^(id error) {
        self.isLoadingData = YES;
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0,*)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //     主列表
    self.adapter.dataSource = self;
    self.adapter.delegate = self;
    self.adapter.collectionView = self.collectionView;
    self.adapter.scrollViewDelegate = self;

    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadDataSource];
    }];
    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    self.collectionView.mj_footer = footer;
    self.collectionView.mj_footer.hidden = YES;
    
    
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = [UIColor whiteColor];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
   
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-kNavBarHeight - 50);
        make.centerX.equalTo(self.view);
    }];
    
    self.noDateLb = [[UILabel alloc]init];
    self.noDateLb.text = @"无内容";
    self.noDateLb.textColor = C153;
    self.noDateLb.font = font(12);
    self.noDateLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDateLb];
    [self.noDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
    
    self.page = 1;
    
    [self loadDataSource];
            
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.currentIndex = -1;
    self.lastIndex = -1;
    self.isTop = YES;
    
    self.dataView = [[UIView alloc]init];
    self.dataView.backgroundColor = RGBA(240, 240, 240, 1);
    [self.view addSubview:self.dataView];
    
    self.dataLb = [[UILabel alloc]init];
    self.dataLb.font = font(10);
    self.dataLb.textColor = C51;
    [self.dataView addSubview:self.dataLb];
    [self.dataView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        }else{
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
        }
        make.top.equalTo(self.view);
        make.height.mas_equalTo(32);
    }];
    [self.dataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dataView).offset(16);
        make.centerY.equalTo(self.dataView);
    }];

//    self.dataLine = [[UIView alloc]init];
//    self.dataLine.backgroundColor = RGBA(58, 64, 79, 1);
//    [self.dataView addSubview:self.dataLine];
//    [self.dataLine mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.equalTo(self.dataView);
//        make.height.mas_equalTo(0.5);
//    }];
    
    
    self.dataView.alpha = 0;
    
    self.isHideNavBar = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfoList) name:@"updateUserInfoList" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteHomePageItem:) name:@"deleteHomePageItem" object:nil];
}

- (void)updateUserInfoList{
    // 还原初始化设置
    
    self.page = 1;
    
    [self resetConfigure];
    
    [self loadDataSource];
}

- (void)resetConfigure{
    
    self.currentIndex = -1;
    
    self.lastIndex = -1;
    
    self.lastModel = nil;
    
    self.isTop = YES;
    
    self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
    
    [self.collectionView.mj_footer resetNoMoreData];
}

- (void)loadDataSource{
    self.isBeginScroll = NO;
    self.isLoadingData = NO;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = self.userId;
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @(10);
    param[@"type"] = @"1";
    param[@"checked"] = @(1);
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPostList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPostList) parames:param success:^(id responseObj) {
       
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        self.isLoadingData = YES;
        
        if (self.page == 1) {
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            HomePageItemModel *model = [self.dataArray firstObject];
            self.dataLb.text = model.yearStr;
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        [self.adapter performUpdatesAnimated:NO completion:^(BOOL finished) {
            if (finished) {
                CGFloat bottom = self.collectionView.mj_insetB;
                self.isLastPage = ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]);
                if (self.isLastPage) {
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                    if (self.collectionView.mj_footer.cl_height == 44.0f) {
                        self.collectionView.mj_footer.cl_height = 138.0f;
                        if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                            self.collectionView.mj_insetB = 138.0f;
                        }
                    }
                }else{
                    [self.collectionView.mj_footer resetNoMoreData];
                    if (self.collectionView.mj_footer.cl_height == 138.0f) {
                        self.collectionView.mj_footer.cl_height = 44.0f;
                        if (bottom == 138.0f) {
                            self.collectionView.mj_insetB = 44.0f;
                        }
                    }
                }
                if (self.updateItemCount) {
                    self.updateItemCount([responseObj[RESPONSE][TOTAL] intValue]);
                }
            }
            self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
        }];
    } failure:^(id error) {
        self.isLoadingData = YES;
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        self.page--;
    }];
}

- (void)deleteHomePageItem:(NSNotification *)note{
    [self updateUserInfoList];
}
- (void)updateItemWithCurrentModel:(HomePageItemModel *)itemModel{
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:itemModel.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        [self.dataArray replaceObjectAtIndex:index withObject:itemModel];
    }
    [self.adapter reloadDataWithCompletion:nil];
}

#pragma mark - JXPagingViewListViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.collectionView;
}


- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
    CGFloat hight = scrollView.frame.size.height;
    CGFloat contentOffset = scrollView.contentOffset.y;
    CGFloat distanceFromBottom = scrollView.contentSize.height - contentOffset;
    CGFloat offset = contentOffset - self.lastcontentOffset;
    self.lastcontentOffset = contentOffset;

    if (offset > 0 && contentOffset > 0) {
        self.dataView.alpha = self.dataArray.count > 0;
        self.isTop = YES;
    }
    if (offset < 0 && distanceFromBottom > hight) {
        self.isTop = NO;
    }
    if (scrollView.contentOffset.y <= 0) {
        self.dataView.alpha = 0;
        self.currentIndex = -1;
        self.lastIndex = -1;
    }
    
    if (self.currentIndex != -1) {
        HomePageItemModel *model = self.dataArray[self.currentIndex];
        self.dataLb.text = model.yearStr;
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.dataLb.alpha = 1;
    self.isBeginScroll = YES;
}

#pragma mark - IGListAdapterDataSource
- (NSArray<id <IGListDiffable>> *)objectsForListAdapter:(IGListAdapter *)listAdapter{
    self.noDataView.hidden = self.dataArray.count > 0;
    return self.dataArray;
}

- (IGListSectionController *)listAdapter:(IGListAdapter *)listAdapter sectionControllerForObject:(id)object{
    self.lastModel = object;
    if ([(HomePageItemModel *)object contentType].intValue == 1) {
        HomeUserInfoDynamicContentViewController *vc = [[HomeUserInfoDynamicContentViewController alloc]init];
        if (self.lastModel.contentType.intValue == 4) {
            vc.inset = UIEdgeInsetsMake(4, 0,0, 0);
        }else{
            vc.inset = UIEdgeInsetsMake(16, 0,0, 0);
        }
        vc.model = object;
        __weak typeof(self)weakSelf = self;
        vc.showDtl = ^(HomePageItemModel * _Nonnull itemModel) {
            [weakSelf showDetailVCWithCurrentModel:itemModel];
        };
        return vc;
    }

    HomeUserInfoDynamicImageViewController *vc = [[HomeUserInfoDynamicImageViewController alloc]init];
    vc.model = object;
    if (self.lastModel.contentType.intValue == 4) {
        vc.inset = UIEdgeInsetsMake(4, 0,0, 0);
    }else{
        vc.inset = UIEdgeInsetsMake(16, 0,0, 0);
    }
    
    __weak typeof(self)weakSelf = self;
    vc.showDetail = ^(HomePageItemModel * _Nonnull itemModel) {
        [weakSelf showDetailVCWithCurrentModel:itemModel];
    };
    return vc;
}

- (void)showDetailVCWithCurrentModel:(HomePageItemModel *)itemModel{
    itemModel.currentIndex = 0;
    NSInteger index = [self.dataArray indexOfObject:itemModel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kXHItemType] = @(XHPageDetailItemTypeMix);
    param[kXHPlatformType] = @(XHPageDetailPlatformTypeUserList);
    param[kXHShowUserInfo] = @(NO);
    param[kXHCurrentPage] = @(self.page);
    param[kXHCurrentIndex] = @(index);
    param[kXHListSource] = self.dataArray;
    param[kXHUserCreateTime] = @(YES);
    HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];

    [self.navigationController pushViewController:dtlVC animated:YES];
}

- (nullable UIView *)emptyViewForListAdapter:(IGListAdapter *)listAdapter{
    
    return [UIView new];
}
- (void)listAdapter:(IGListAdapter *)listAdapter willDisplayObject:(id)object atIndex:(NSInteger)index{
    
    if (!self.isTop && self.isBeginScroll && self.isLoadingData) {
        if (labs(index - self.lastIndex) > 1  && self.lastIndex != -1) {
            return;
        }
        self.lastIndex = index;
        self.currentIndex = index;
    }
}

- (void)listAdapter:(IGListAdapter *)listAdapter didEndDisplayingObject:(id)object atIndex:(NSInteger)index{
    if (self.isTop && self.isBeginScroll && self.isLoadingData) {
        if (labs(index - self.lastIndex) > 1 && self.lastIndex != -1) {
            return;
        }
        self.currentIndex = index;
        self.lastIndex = index;
    }
}

- (void)dealloc{
    
}


@end
